#include <iostream>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Comm.hpp"
using namespace std;

void Usage(std::string proc)// 提示说明
{
    cout << "Usage: \n\t" << proc << " server_ip server_port\n" << endl;
}

// ./udp_client server_ip server_port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 1.创建socket
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        cerr << "socket error: " << strerror(errno) << endl;
        return 1;
    }
    cout << "create socket success: " << sock << endl;
    // 2.client也要绑定(bind)，但是不需要显示bind，client会在首次发送数据的时候自动进行bind
    // 为什么?server端的端口号一定是众所周知的，不可改变的， client需要 port ,bind随机端口
    // 因为client非常多， 避免冲突

    //填充server信息
    struct sockaddr_in server;
    memset(&server,0 ,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());//字符串转4字节整数形式
    while(1)
    {
        string inbuffer;
        cout << "Please Enter#";
        getline(cin, inbuffer);
        cout << inbuffer << endl;

        ssize_t n = sendto(sock, inbuffer.c_str(), inbuffer.size(), 0, (sockaddr*)&server, sizeof(server));
        if(n > 0)
        {
            char buffer[1024];
            //收消息
            struct sockaddr temp;// temp和len用来接收
            socklen_t len;
            ssize_t m = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (sockaddr*)&temp, &len);
            if(m > 0)
            {
                buffer[m] = 0;
                cout << "server echo# " << buffer << endl;
            }
            else{
                break;
            }
        }
        else break;
    }
    close(sock);
    return 0;
}